package com.zws.cucumber.tests.springboot.configuration;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;

import javax.annotation.PostConstruct;

@Configuration
public class ZwsSpringBootDemoApplicationTestConf implements EnvironmentAware, ApplicationContextAware {

    private Environment env;

    private ApplicationContext ctx;

    @PostConstruct
    public void init() {
        PropertySource<ApplicationContext> source = new PropertySource<>("outboundPropertySource", ctx) {
            @Override
            public Object getProperty(String name) {
                if ("outbound.port".equals(name)) {
                    return ctx.getEnvironment().getProperty("wiremock.port");
                }
                return null;
            }
        };
        ((ConfigurableEnvironment) env).getPropertySources().addFirst(source);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }
}
